package org.jvm.instruction.references.array.newarray;

import org.jvm.instruction.base.*;
import org.jvm.rtda.Object;
import org.jvm.rtda.heap.Klass;
import org.jvm.rtda.heap.classLoader.KlassLoaderRegister;
import org.jvm.rtda.thread.*;

import java.util.*;

/**
 * 创建基本类型数组
 * 8位操作数为基本类型的枚举
 *
 * @author 海燕
 * @date 2023/2/14
 */
public class NEW_ARRAY extends Index8Instruction {

    //操作数对应的基本类型枚举
    public static final Map<Integer, String> typeMap = new HashMap<Integer, String>() {
        {
            put(4, "[Z");
            put(5, "[C");
            put(6, "[F");
            put(7, "[D");
            put(8, "[B");
            put(9, "[S");
            put(10, "[I");
            put(11, "[J");
        }
    };

    @Override
    public void execute(Frame frame) {
        OperandStack operandStack = frame.getOperandStack();
        //数组长度
        int count = operandStack.popInt();
        String arrayClassName = typeMap.get(this.index);
        //数组里直接使用根类加载器进行加载
        Klass arrayClass = KlassLoaderRegister.getBootKlassLoader().loadKlass(arrayClassName);
        Object arrObject = InstructionUtil.newMultDimensionalArray(0, new int[]{count}, arrayClass);
        operandStack.pushRef(arrObject);
    }
}
